/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entities.Veterinary;
import java.util.ArrayList;
import java.util.List;
import Entities.Owner;
import Entities.Employee;
import Entities.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Heinz Hernandez
 */
public class PersonJpaController implements Serializable {

    public PersonJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Person person) {
        if (person.getVeterinaryList() == null) {
            person.setVeterinaryList(new ArrayList<Veterinary>());
        }
        if (person.getOwnerList() == null) {
            person.setOwnerList(new ArrayList<Owner>());
        }
        if (person.getEmployeeList() == null) {
            person.setEmployeeList(new ArrayList<Employee>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Veterinary> attachedVeterinaryList = new ArrayList<Veterinary>();
            for (Veterinary veterinaryListVeterinaryToAttach : person.getVeterinaryList()) {
                veterinaryListVeterinaryToAttach = em.getReference(veterinaryListVeterinaryToAttach.getClass(), veterinaryListVeterinaryToAttach.getVetId());
                attachedVeterinaryList.add(veterinaryListVeterinaryToAttach);
            }
            person.setVeterinaryList(attachedVeterinaryList);
            List<Owner> attachedOwnerList = new ArrayList<Owner>();
            for (Owner ownerListOwnerToAttach : person.getOwnerList()) {
                ownerListOwnerToAttach = em.getReference(ownerListOwnerToAttach.getClass(), ownerListOwnerToAttach.getOwnId());
                attachedOwnerList.add(ownerListOwnerToAttach);
            }
            person.setOwnerList(attachedOwnerList);
            List<Employee> attachedEmployeeList = new ArrayList<Employee>();
            for (Employee employeeListEmployeeToAttach : person.getEmployeeList()) {
                employeeListEmployeeToAttach = em.getReference(employeeListEmployeeToAttach.getClass(), employeeListEmployeeToAttach.getEmplId());
                attachedEmployeeList.add(employeeListEmployeeToAttach);
            }
            person.setEmployeeList(attachedEmployeeList);
            em.persist(person);
            for (Veterinary veterinaryListVeterinary : person.getVeterinaryList()) {
                Person oldPerIdOfVeterinaryListVeterinary = veterinaryListVeterinary.getPerId();
                veterinaryListVeterinary.setPerId(person);
                veterinaryListVeterinary = em.merge(veterinaryListVeterinary);
                if (oldPerIdOfVeterinaryListVeterinary != null) {
                    oldPerIdOfVeterinaryListVeterinary.getVeterinaryList().remove(veterinaryListVeterinary);
                    oldPerIdOfVeterinaryListVeterinary = em.merge(oldPerIdOfVeterinaryListVeterinary);
                }
            }
            for (Owner ownerListOwner : person.getOwnerList()) {
                Person oldPerIdOfOwnerListOwner = ownerListOwner.getPerId();
                ownerListOwner.setPerId(person);
                ownerListOwner = em.merge(ownerListOwner);
                if (oldPerIdOfOwnerListOwner != null) {
                    oldPerIdOfOwnerListOwner.getOwnerList().remove(ownerListOwner);
                    oldPerIdOfOwnerListOwner = em.merge(oldPerIdOfOwnerListOwner);
                }
            }
            for (Employee employeeListEmployee : person.getEmployeeList()) {
                Person oldPerIdOfEmployeeListEmployee = employeeListEmployee.getPerId();
                employeeListEmployee.setPerId(person);
                employeeListEmployee = em.merge(employeeListEmployee);
                if (oldPerIdOfEmployeeListEmployee != null) {
                    oldPerIdOfEmployeeListEmployee.getEmployeeList().remove(employeeListEmployee);
                    oldPerIdOfEmployeeListEmployee = em.merge(oldPerIdOfEmployeeListEmployee);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Person person) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person persistentPerson = em.find(Person.class, person.getPerId());
            List<Veterinary> veterinaryListOld = persistentPerson.getVeterinaryList();
            List<Veterinary> veterinaryListNew = person.getVeterinaryList();
            List<Owner> ownerListOld = persistentPerson.getOwnerList();
            List<Owner> ownerListNew = person.getOwnerList();
            List<Employee> employeeListOld = persistentPerson.getEmployeeList();
            List<Employee> employeeListNew = person.getEmployeeList();
            List<Veterinary> attachedVeterinaryListNew = new ArrayList<Veterinary>();
            for (Veterinary veterinaryListNewVeterinaryToAttach : veterinaryListNew) {
                veterinaryListNewVeterinaryToAttach = em.getReference(veterinaryListNewVeterinaryToAttach.getClass(), veterinaryListNewVeterinaryToAttach.getVetId());
                attachedVeterinaryListNew.add(veterinaryListNewVeterinaryToAttach);
            }
            veterinaryListNew = attachedVeterinaryListNew;
            person.setVeterinaryList(veterinaryListNew);
            List<Owner> attachedOwnerListNew = new ArrayList<Owner>();
            for (Owner ownerListNewOwnerToAttach : ownerListNew) {
                ownerListNewOwnerToAttach = em.getReference(ownerListNewOwnerToAttach.getClass(), ownerListNewOwnerToAttach.getOwnId());
                attachedOwnerListNew.add(ownerListNewOwnerToAttach);
            }
            ownerListNew = attachedOwnerListNew;
            person.setOwnerList(ownerListNew);
            List<Employee> attachedEmployeeListNew = new ArrayList<Employee>();
            for (Employee employeeListNewEmployeeToAttach : employeeListNew) {
                employeeListNewEmployeeToAttach = em.getReference(employeeListNewEmployeeToAttach.getClass(), employeeListNewEmployeeToAttach.getEmplId());
                attachedEmployeeListNew.add(employeeListNewEmployeeToAttach);
            }
            employeeListNew = attachedEmployeeListNew;
            person.setEmployeeList(employeeListNew);
            person = em.merge(person);
            for (Veterinary veterinaryListOldVeterinary : veterinaryListOld) {
                if (!veterinaryListNew.contains(veterinaryListOldVeterinary)) {
                    veterinaryListOldVeterinary.setPerId(null);
                    veterinaryListOldVeterinary = em.merge(veterinaryListOldVeterinary);
                }
            }
            for (Veterinary veterinaryListNewVeterinary : veterinaryListNew) {
                if (!veterinaryListOld.contains(veterinaryListNewVeterinary)) {
                    Person oldPerIdOfVeterinaryListNewVeterinary = veterinaryListNewVeterinary.getPerId();
                    veterinaryListNewVeterinary.setPerId(person);
                    veterinaryListNewVeterinary = em.merge(veterinaryListNewVeterinary);
                    if (oldPerIdOfVeterinaryListNewVeterinary != null && !oldPerIdOfVeterinaryListNewVeterinary.equals(person)) {
                        oldPerIdOfVeterinaryListNewVeterinary.getVeterinaryList().remove(veterinaryListNewVeterinary);
                        oldPerIdOfVeterinaryListNewVeterinary = em.merge(oldPerIdOfVeterinaryListNewVeterinary);
                    }
                }
            }
            for (Owner ownerListOldOwner : ownerListOld) {
                if (!ownerListNew.contains(ownerListOldOwner)) {
                    ownerListOldOwner.setPerId(null);
                    ownerListOldOwner = em.merge(ownerListOldOwner);
                }
            }
            for (Owner ownerListNewOwner : ownerListNew) {
                if (!ownerListOld.contains(ownerListNewOwner)) {
                    Person oldPerIdOfOwnerListNewOwner = ownerListNewOwner.getPerId();
                    ownerListNewOwner.setPerId(person);
                    ownerListNewOwner = em.merge(ownerListNewOwner);
                    if (oldPerIdOfOwnerListNewOwner != null && !oldPerIdOfOwnerListNewOwner.equals(person)) {
                        oldPerIdOfOwnerListNewOwner.getOwnerList().remove(ownerListNewOwner);
                        oldPerIdOfOwnerListNewOwner = em.merge(oldPerIdOfOwnerListNewOwner);
                    }
                }
            }
            for (Employee employeeListOldEmployee : employeeListOld) {
                if (!employeeListNew.contains(employeeListOldEmployee)) {
                    employeeListOldEmployee.setPerId(null);
                    employeeListOldEmployee = em.merge(employeeListOldEmployee);
                }
            }
            for (Employee employeeListNewEmployee : employeeListNew) {
                if (!employeeListOld.contains(employeeListNewEmployee)) {
                    Person oldPerIdOfEmployeeListNewEmployee = employeeListNewEmployee.getPerId();
                    employeeListNewEmployee.setPerId(person);
                    employeeListNewEmployee = em.merge(employeeListNewEmployee);
                    if (oldPerIdOfEmployeeListNewEmployee != null && !oldPerIdOfEmployeeListNewEmployee.equals(person)) {
                        oldPerIdOfEmployeeListNewEmployee.getEmployeeList().remove(employeeListNewEmployee);
                        oldPerIdOfEmployeeListNewEmployee = em.merge(oldPerIdOfEmployeeListNewEmployee);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = person.getPerId();
                if (findPerson(id) == null) {
                    throw new NonexistentEntityException("The person with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person person;
            try {
                person = em.getReference(Person.class, id);
                person.getPerId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The person with id " + id + " no longer exists.", enfe);
            }
            List<Veterinary> veterinaryList = person.getVeterinaryList();
            for (Veterinary veterinaryListVeterinary : veterinaryList) {
                veterinaryListVeterinary.setPerId(null);
                veterinaryListVeterinary = em.merge(veterinaryListVeterinary);
            }
            List<Owner> ownerList = person.getOwnerList();
            for (Owner ownerListOwner : ownerList) {
                ownerListOwner.setPerId(null);
                ownerListOwner = em.merge(ownerListOwner);
            }
            List<Employee> employeeList = person.getEmployeeList();
            for (Employee employeeListEmployee : employeeList) {
                employeeListEmployee.setPerId(null);
                employeeListEmployee = em.merge(employeeListEmployee);
            }
            em.remove(person);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Person> findPersonEntities() {
        return findPersonEntities(true, -1, -1);
    }

    public List<Person> findPersonEntities(int maxResults, int firstResult) {
        return findPersonEntities(false, maxResults, firstResult);
    }

    private List<Person> findPersonEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Person.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Person findPerson(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Person.class, id);
        } finally {
            em.close();
        }
    }

    public int getPersonCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Person> rt = cq.from(Person.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
